<template>
  <div>
    <div class="full-screen">
      <div class="form">
        <div class="block">
          <div class="group hairlines-bottom">
            <label for="real_name">姓名</label>
            <input id="real_name" type="text" placeholder="请输入姓名" v-model="base.real_name">
          </div>
          <div class="group hairlines-bottom">
            <label for="id_card_no">身份证</label>
            <input id="id_card_no" type="text" placeholder="请输入身份证号" v-model="base.id_card_no">
          </div>
          <div class="group hairlines-bottom">
            <label for="mobile">手机号码</label>
            <input id="mobile" type="number" placeholder="请输入手机号码" ref="phone" @input="checkPhone" v-model="base.mobile">
          </div>
          <div class="group">
            <label for="code">验证码</label>
            <div class="with-bt">
              <input class="code" id="code" type="number" placeholder="请输入验证码" v-model="base.code">
              <input class="codebt-s" type="button" :value="codetext" @click="sendCode" ref="sendBt">
            </div>
          </div>
        </div>
        <div class="block">
          <div class="group hairlines-bottom">
            <label for="salary">打卡工资/生活费</label>
            <input id="salary" type="number" placeholder="请输入工资" v-model="base.salary">
          </div>
          <div class="group hairlines-bottom isSelect">
            <label for="education">教育程度</label>
            <input id="education" type="text" placeholder="请选择" readonly @click="showSelect($event, 'education')" v-model="base.education_name" :data-id="base.education">
          </div>
          <div class="group hairlines-bottom isSelect">
            <label for="residence">户口类型</label>
            <input id="residence" type="text" placeholder="请选择" readonly @click="showSelect($event, 'residence')" v-model="base.residence_name" :data-id="base.residence">
          </div>
          <div class="group hairlines-bottom isSelect">
            <label for="marriage">婚姻状况</label>
            <input id="marriage" type="text" placeholder="请选择" readonly @click="showSelect($event, 'marriage')" v-model="base.marriage_name" :data-id="base.marriage">
          </div>
          <div class="group hairlines-bottom isSelect">
            <label for="ownAddress">居住地址</label>
            <input id="ownAddress" type="text" placeholder="请选择" readonly v-model="base.ownAddress" :data-pid="base.pid" :data-cid="base.cid" :data-rid="base.rid" @click="showAddress">
          </div>
          <div class="detail-address">
            <textarea id="address" placeholder="请输入详细地址" v-model="base.address"></textarea>
          </div>
        </div>
        <div class="block">
          <div class="group isSelect">
            <label for="has_job">工作状态</label>
            <input id="has_job" type="text" placeholder="请选择" readonly :value="+base.has_job === 0 ? '无工作' : '有工作'" :data-id="base.has_job" @click="showSelect($event, 'jobDatas')">
          </div>
        </div>
        <div class="block" v-if="+base.has_job === 1">
          <div class="group hairlines-bottom">
            <label for="company">单位名称</label>
            <input id="company" type="text" placeholder="请输入名称" @focus="intoView" v-model="base.company">
          </div>
          <div class="group hairlines-bottom">
            <label for="job">担任职位</label>
            <input id="job" type="text" placeholder="请输入职位" @focus="intoView" v-model="base.job">
          </div>
          <div class="group hairlines-bottom">
            <label for="company_tel">单位电话</label>
            <input id="company_tel" type="number" placeholder="请输入电话" @focus="intoView" v-model="base.company_tel">
          </div>
          <div class="group hairlines-bottom isSelect">
            <label for="job_time">入职时间</label>
            <input id="job_time" type="text" placeholder="请选择" readonly @click="showTime" v-model="base.job_time" :data-id="base.job_time">
          </div>
          <div class="group hairlines-bottom isSelect">
            <label for="companyAddress">单位地址</label>
            <input id="companyAddress" type="text" placeholder="请选择" readonly @click="showAddress" v-model="base.companyAddress" :data-cpid="base.cpid" :data-ccid="base.ccid" :data-crid="base.crid">
          </div>
          <div class="detail-address">
            <textarea id="caddress" placeholder="请输入详细地址" @focus="intoView" v-model="base.caddress"></textarea>
          </div>
        </div>
        <div class="file-block" v-else>
          <h4 class="hairlines-bottom">信用卡或医保卡<span>(无业必填)</span></h4>
          <div class="photo">
            <div class="container">
              <img ref="jobToImg" :src="base.no_job_card === null ? defaultImg : base.no_job_card">
              <input ref="jobInput" id="no_job_card" type="file">
            </div>
          </div>
        </div>
        <div class="file-block">
          <h4 class="hairlines-bottom">上传暂住证<span>(非本地户口必填)</span></h4>
          <div class="photo">
            <div class="container">
              <img ref="fileToImg" :src="base.residence_permit === null ? defaultImg : base.residence_permit">
              <input id="residence_permit" type="file" ref="fileInput">
            </div>
          </div>
        </div>
      </div>
      <footer class="form-footer">
        <button class="return hairlines-top" @click="back"><i class="iconfont icon-return2"></i>返回</button>
        <input class="next" type="button" value="保存，下一步" @click="toNext">
      </footer>
    </div>
    <select-tem :selectDatas="selectDatas" @hideSelect="hideSelect" @selectConfirm="selectConfirm" v-if="selectIsShow"></select-tem>
    <address-tem @hideAddress="hideAddress" @addressConfirm="addressConfirm" v-if="addressIsShow" @addLoading="addLoading" @delLoading="delLoading"></address-tem>
    <time-tem :startYear="2010" @hideTime="hideTime" @timeConfirm="timeConfirm" :timeIsShow= "timeIsShow"></time-tem>
    <loading-tem v-if="loadingIsShow" :show="loadingIsShow"></loading-tem>
  </div>
</template>
<script>
  import $ from 'edom'
  import select from '../select/select.vue'
  import address from '../address/address.vue'
  import time from '../time/time.vue'
  import loading from '../loading/loading.vue'
  import fileRead from '../../assets/js/fileRead.js'
  import photoImg from '../../assets/img/info-photo.png'

  export default {
    name: 'Info',
    components: {
      'select-tem': select,
      'address-tem': address,
      'time-tem': time,
      'loading-tem': loading
    },
    data () {
      return {
        title: '担保人信息',
        selectIsShow: false,
        addressIsShow: false,
        timeIsShow: false,
        loadingIsShow: false,
        currentTarget: null,
        base64Img: null,
        base64Img2: null,
        time: 60,
        codetext: '获取验证码',
        defaultImg: photoImg,
        selectDatas: {
          title: '户口类型',
          lists: [
            {id: 0, value: '外地户口'},
            {id: 1, value: '本地户口'}
          ]
        },
        accountTypeDatas: {
          title: '户口类型',
          lists: [
            {id: 0, value: '外地户口'},
            {id: 1, value: '本地户口'}
          ]
        },
        degreeDatas: {
          title: '教育程度',
          lists: [
            {id: 1, value: '硕士'},
            {id: 2, value: '本科'},
            {id: 3, value: '大专'},
            {id: 4, value: '高中'}
          ]
        },
        marriageDatas: {
          title: '婚姻状况',
          lists: [
            {id: 0, value: '已婚'},
            {id: 1, value: '未婚'},
            {id: 2, value: '离异'},
            {id: 3, value: '丧偶'}
          ]
        },
        jobDatas: {
          title: '工作状态',
          lists: [
            {id: 0, value: '无工作'},
            {id: 1, value: '有工作'}
          ]
        }
      }
    },
    computed: {
      base () {
        return this.$store.state.warrantor.base
      }
    },
    methods: {
      back: function () {
        this.$router.push('/warrantor/manage')
      },
      toNext: function () {
        $().Mconfirm({
          desc: '是否同意为借款人提供担保？',
          confirmBt: () => {
            this.checkInfo()
          }
        })
      },
      checkInfo: async function () {
        let required = ['real_name', 'id_card_no', 'mobile', 'code', 'salary', 'education', 'pid', 'residence', 'marriage', 'address']
        let hasJob = this.base.has_job
        // 无工作
        if (!hasJob) {
          // 要填写医保卡或信用卡
          if (!this.$refs.jobInput.value) {
            $().Mnews('请上传信用卡或医保卡', 1000)
            return
          }
        } else {
          // 要填写工作相关的字段
          required = required.concat(['company', 'job', 'company_tel', 'job_time', 'cpid', 'caddress'])
        }
        let fileInput = this.$refs.fileInput
        let token = null
        let key = null
        let state = false
        required.map((item, index) => {
          if (!this.base[item]) {
            state = true
          }
        })
        if (state) {
          $().Mnews('有必填项没有填写', 1000)
          return
        }
        if (this.base.residence === '1') {
          // 是本地户口不用必填暂住证
          // 如果上传了图片，那么走七牛云
          this.addLoading()
          if (fileInput.value) {
            token = await this.api.getQNYToken()
            key = await this.api.getQNYKey(this.base64Img, token)
            this.base.residence_permit = key
            this.$store.commit('setCacheWarrantorBase', {residence_permit: key})
          }
        } else {
          // 外地户口必填暂住证
          if (!fileInput.value) {
            $().Mnews('请上传暂住证', 1000)
            return
          }
          this.addLoading()
          token = await this.api.getQNYToken()
          key = await this.api.getQNYKey(this.base64Img, token)
          this.$store.commit('setCacheWarrantorBase', {residence_permit: key})
        }
        if (!hasJob) {
          key = await this.api.getQNYKey(this.base64Img2, token)
          this.base.no_job_card = key
        }
        this.saveInfo()
      },
      saveInfo: function () {
        let fileInput = this.$refs.fileInput
        let jobInput = this.$refs.jobInput
        if (!fileInput.value) {
          this.$store.commit('setCacheBaseInfo', {residence_permit: null})
        }
        if (!jobInput || !jobInput.value) {
          this.$store.commit('setCacheBaseInfo', {no_job_card: null})
        }
        this.axios.post('/api/guarantee/saveInfo', Object.assign({
          user_id: this.$store.state.user_id,
          token: this.$store.state.token
        }, this.$store.state.warrantor.base))
        .then((res) => {
          let data = res.data
          this.delLoading()
          if (data.code === 200) {
            this.$store.commit('warrantorStepSet', 2)
            this.$router.push('/warrantor/manage')
          } else {
            $().Mnews(data.desc, 3000)
          }
        })
      },
      showSelect: function (event, which) {
        let target = event.target
        this.currentTarget = target
        if (which === 'education') {
          this.selectDatas = this.degreeDatas
        } else if (which === 'residence') {
          this.selectDatas = this.accountTypeDatas
        } else if (which === 'marriage') {
          this.selectDatas = this.marriageDatas
        } else {
          this.selectDatas = this.jobDatas
        }
        this.selectIsShow = true
      },
      hideSelect: function () {
        this.selectIsShow = false
      },
      selectConfirm: function (obj) {
        this.selectIsShow = false
        if (this.currentTarget.id === 'has_job') {
          this.$store.commit('setCacheWarrantorBase', {has_job: obj.id})
        } else {
          let data = {}
          data[this.currentTarget.id + '_name'] = obj.value
          data[this.currentTarget.id] = obj.id
          this.$store.commit('setCacheWarrantorBase', data)
        }
      },
      showAddress: function (event) {
        this.addressIsShow = true
        let target = event.target
        this.currentTarget = target
      },
      hideAddress: function () {
        this.addressIsShow = false
      },
      addressConfirm: function (obj) {
        let text = ''
        this.loadingIsShow = false
        this.addressIsShow = false
        let data = {}
        for (let i = 0; i < obj.length; i++) {
          if (obj[i].value !== '市辖区' && obj[i].value !== '县') {
            text = text + obj[i].value + ' '
          }
          if (i === 0) {
            if (this.currentTarget.id === 'companyAddress') {
              data['cpid'] = obj[0].code
            } else {
              data['pid'] = obj[0].code
            }
          } else if (i === 1) {
            if (this.currentTarget.id === 'companyAddress') {
              data['ccid'] = obj[1].code
            } else {
              data['cid'] = obj[1].code
            }
          } else if (i === 2) {
            if (this.currentTarget.id === 'companyAddress') {
              data['crid'] = obj[2].code
            } else {
              data['rid'] = obj[2].code
            }
          }
        }
        data[this.currentTarget.id] = text
        this.$store.commit('setCacheWarrantorBase', data)
      },
      showTime: function (event) {
        this.timeIsShow = true
        let target = event.target
        this.currentTarget = target
      },
      hideTime: function () {
        this.timeIsShow = false
      },
      timeConfirm: function (value) {
        this.timeIsShow = false
        let data = {}
        data[this.currentTarget.id] = value
        this.$store.commit('setCacheWarrantorBase', data)
      },
      checkPhone: function (event) {
        let phone = event.target
        let value = phone.value
        let length = value.length
        if (length > 11) {
          phone.value = value.substring(0, 11)
        }
      },
      sendCode: function () {
        let Timer = null
        let sendBt = this.$refs.sendBt
        let phone = this.$refs.phone
        if (!$().checkPhone(phone.value)) {
          $().Mnews('请检查手机号', 1000)
          return
        }
        sendBt.setAttribute('disabled', 'disabled')
        this.codetext = `剩余(${this.time}s)`
        Timer = setInterval(() => {
          if (this.time <= 1) {
            clearInterval(Timer)
            sendBt.removeAttribute('disabled')
            this.time = 60
            this.codetext = '获取校验码'
          } else {
            this.time--
            this.codetext = `剩余(${this.time}s)`
          }
        }, 1000)
        this.axios.post('/api/sms/send_code', {
          mobile: phone.value
        }).then((res) => {
          let data = res.data
          if (data.code !== 200) {
            $().Mnews(data.desc)
          }
        })
      },
      addLoading: function () {
        this.loadingIsShow = true
      },
      delLoading: function () {
        this.loadingIsShow = false
      },
      intoView: function (event) {
        event.target.scrollIntoView(true)
      }
    },
    created () {
      this.setTitle(this.title)
    },
    mounted () {
      let file = this.$refs
      fileRead(file.fileInput, {
        readAs: 'dataurl',
        zip: true,
        zipWidth: file.offsetWidth * 2,
        zipQuality: 0.7,
        loadStart: () => {
          this.addLoading()
        },
        loadEnd: () => {
          setTimeout(() => {
            this.delLoading()
          }, 300)
        },
        success: (result, resultHandle) => {
          this.base64Img = resultHandle[0]
          file.fileToImg.setAttribute('src', result[0])
        },
        error: function (msg) {
          $().Mnews(msg, 1000)
        }
      })
      fileRead(file.jobInput, {
        readAs: 'dataurl',
        zip: true,
        zipWidth: file.offsetWidth * 2,
        zipQuality: 0.7,
        loadStart: () => {
          this.addLoading()
        },
        loadEnd: () => {
          setTimeout(() => {
            this.delLoading()
          }, 300)
        },
        success: (result, resultHandle) => {
          this.base64Img2 = resultHandle[0]
          file.jobToImg.setAttribute('src', result[0])
        },
        error: function (msg) {
          $().Mnews(msg, 1000)
        }
      })
    }
  }
</script>
<style lang="scss" scoped>
  @import '../../styles/form.scss';
  .form{
    .block{
      .group{
        .with-bt{
          display: flex;
          align-items: center;
        }
        .code{
          flex: 1;
          margin-right: rem(20);
          font-size: rem(28);
          color: #333;
          text-align: right;
        }
        .codebt-s{
          width: rem(160);
          height: rem(50);
          background: #fff;
          font-size: rem(24);
          color: #72a5ef;
          border-radius: 16px;
          border: 1px solid #72a5ef;
          text-align: center;
        }
      }
    }
  }
</style>
